using IQIGame.Onigao.Game;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// npc跟随玩家组件
    /// </summary>
    public class LgFollowHeroComponent : LogicBaseEntityComponent
    {
        public override uint MaxStore => 5;
        private LevelEntity _entity;
        private LevelHeroEntity _hero;
        private bool _isNaving = false;
        private Vector3Logic _lastHeroPos;

        public override void Awake(BaseEntity entity)
        {
            _entity = (LevelEntity)entity;
        }

        public void SetHero(LevelHeroEntity heroEntity)
        {
            _hero = heroEntity;
            _hero.player.entityFollowingMe = _entity;
            _isNaving = false;
        }

        public override void LogicOnUpdate()
        {
            if (_hero != null)
            {
                Vector3Logic heroToEntity = _entity.position - _hero.position;
                //小于跟随距离则不跟随
                if (heroToEntity.sqrMagnitude > LgLevelConst.SqrFollowDistance)
                {
                    if ((_lastHeroPos - _hero.position).sqrMagnitude > 10)
                    {
                        _isNaving = true;
                        _lastHeroPos = _hero.position;
                        _entity.StartNavigation(_hero.position, false, _hero.moveSpeed);
                    }
                }
                else
                {
                    if (_isNaving)
                    {
                        _isNaving = false;
                        _entity.StopNavigation(false);
                    }
                }
                var dir = _hero.position - _entity.position;
                dir.y = 0;
                _entity.dirUnnormalized = dir;
            }
        }
        public override void OnRelease()
        {
            if (_isNaving)
            {
                _isNaving = false;
                _entity.StopNavigation(true);
            }
            if (_hero != null)
            {
                _hero.player.entityFollowingMe = null;
                _hero = null;
            }
            _entity = null;
        }
    }
}
